<template>
  <div>
    <!-- 按钮 -->
    <div class="operation-group">
      <dialogMultiSelectTable
        btnText="选择库存"
        dialogTitle="选择库存"
        onlyKey="batchNumber"
        :isShow="getInventoryStatus"
        isOpenSearch
        errorMessage="请先选择仓库"
        :searchInputArr="jsList.planSearchInputArr"
        :tableHeadOptions="jsList.planTableHeadOptions"
        :getTableList="listSmpStockForInventoryPage"
        :optionalParams="planOptionalParams"
        @confirm="planConfirm"
      />
      <dialogMultiSelectTable
        btnText="盘0库存"
        dialogTitle="选择盘0库存"
        onlyKey="batchNumber"
        :isShow="getInventoryStatus"
        isOpenSearch
        errorMessage="请先选择仓库"
        :searchInputArr="jsList.planSearchInputArr"
        :tableHeadOptions="jsList.planTableHeadOptions"
        :getTableList="listPageInventoryZero"
        :optionalParams="planOptionalParams"
        @confirm="planConfirmZero"
      />
      <el-button class="ml" plain type="single-number" @click="handleRemove"
        >删除行
      </el-button>
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <ux-grid
        ref="tableList"
        widthResize
        keep-source
        show-overflow="title"
        :header-cell-class-name="must"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
        @selection-change="listSelectTable"
        show-summary
        :summary-method="getSummaries"
      >
        <ux-table-column
          type="checkbox"
          min-width="50"
          align="center"
          fixed="left"
        />

        <ux-table-column
          title="序号"
          type="index"
          align="center"
          min-width="55"
          fixed="left"
        />

        <ux-table-column
          show-overflow-tooltip
          field="batchNumber"
          title="批次号"
          min-width="200"
          fixed="left"
          resizable
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="materialCode"
          title="设备物资编码"
          min-width="150"
        >
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="materialName"
          title="设备物资名称"
          min-width="300"
        />

        <ux-table-column
          show-overflow-tooltip
          field="materialState"
          title="设备物资说明"
          min-width="150"
          resizable
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input
              maxlength="500"
              v-model="row.materialState"
              show-word-limit
            />
          </template>
          <template v-slot="{ row }">
            <span class="my-input-sc">{{ row.materialState }} </span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="categoryName"
          title="分类名称"
          min-width="130"
          resizable
        />
        <ux-table-column
          show-overflow-tooltip
          field="measureUnit"
          title="计量单位"
          min-width="130"
          resizable
        />
        <ux-table-column
          show-overflow-tooltip
          field="storageCount"
          title="入库数量"
          min-width="130"
          resizable
        />
        <ux-table-column
          show-overflow-tooltip
          field="unStockCount"
          title="当前库存数量"
          min-width="130"
          resizable
        />

        <ux-table-column
          field="inventoryCount"
          title="盘点数量"
          min-width="140"
          resizable
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input
              v-model="row.inventoryCount"
              @blur="testColumn($event, row, 'blur', 'inventoryCount')"
              @focus="testColumn($event, row, 'focus', 'inventoryCount')"
            />
          </template>
          <template v-slot="{ row }">
            <span :class="'my-input-sc'">{{ row.inventoryCount }} </span>
          </template>
        </ux-table-column>

        <ux-table-column
          show-overflow-tooltip
          field="currencyName"
          title="币种"
          min-width="130"
          resizable
        />

        <ux-table-column
          show-overflow-tooltip
          field="exchangeRate"
          title="汇率"
          min-width="130"
          resizable
        />

        <ux-table-column
          field="unitPriceWithTax"
          title="含税单价"
          align="right"
          header-align="left"
          min-width="140"
          resizable
          show-overflow="none"
        >
        </ux-table-column>
        <ux-table-column
          field="moneyWithTax"
          title="含税金额"
          align="right"
          header-align="left"
          min-width="140"
          resizable
          show-overflow="none"
        >
        </ux-table-column>
        <ux-table-column
          show-overflow-tooltip
          field="inventoryDifferences"
          title="差异"
          min-width="130"
          resizable
        />
        <ux-table-column
          show-overflow-tooltip
          field="remark"
          title="备注"
          min-width="150"
          resizable
          :edit-render="{ autofocus: '.el-input__inner' }"
        >
          <template v-slot:edit="{ row }">
            <el-input maxlength="1000" v-model="row.remark" show-word-limit />
          </template>
          <template v-slot="{ row }">
            <span class="my-input-sc">{{ row.remark }} </span>
          </template>
        </ux-table-column>
      </ux-grid>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import publicComponent from "@/basa/components/public";
import jsList from "../js";
import { showLoading } from "@/basa/utils/public";
import { uniqueByJson, setToFixed } from "@/basa/utils";
import { listSmpStockForInventoryPage, listPageInventoryZero } from "../api";
import { formatNumber } from "@/basa/utils";
export default {
  props: {
    detail: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    dialogMultiSelectTable: publicComponent.dialogMultiSelectTable
  },
  data() {
    return {
      jsList,
      listTableData: [],
      tableList: [],
      timer: null,
      tableLoading: null,
      planOptionalParams: {},
      // 计算总和的字段
      summaryArr: ["inventoryCount", "inventoryDifferences"]
    };
  },
  computed: {
    ...mapGetters(["getWarehouseId", "getInventoryStatus", "getReportChange"])
  },
  created() {
    this.init();
    this.$once("hook:beforeDestroy", () => {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    });
  },
  watch: {
    getWarehouseId: {
      handler(val) {
        if (val) {
          this.planOptionalParams = {
            ...this.planOptionalParams,
            warehouseId: val
          };
        }
      },
      immediate: true
    },
    getReportChange(val) {
      if (val) {
        this.tableList = [];
        this.setDetailedTableList();
        this.setReportChange(false);
      }
    }
  },
  methods: {
    listSmpStockForInventoryPage,
    listPageInventoryZero,
    init() {
      if (this.detail.state === "edit") {
        this.editInit();
      }
    },
    editInit() {
      this.tableList = this.detail.inventoryBOList.map(item => ({
        ...item,
        storageCount:
          item.storageCount !== null
            ? Number(item.storageCount).toFixed(3)
            : "",
        unStockCount:
          item.unStockCount !== null
            ? Number(item.unStockCount).toFixed(3)
            : "",
        inventoryCount:
          item.inventoryCount !== null
            ? Number(item.inventoryCount).toFixed(3)
            : "",
        inventoryDifferences:
          item.inventoryDifferences !== null
            ? Number(item.inventoryDifferences).toFixed(3)
            : "",
        unitPriceWithTax:
          item.unitPriceWithTax !== null
            ? Number(item.unitPriceWithTax).toFixed(2)
            : "",
        moneyWithTax:
          item.moneyWithTax !== null ? Number(item.moneyWithTax).toFixed(2) : ""
      }));
      this.setDetailedTableList();
    },

    // 删除行
    handleRemove() {
      if (!this.listTableData.length) {
        this.$showErrorMessage("未选中复选框");
      } else {
        this.$confirm("是否确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let temp = new Set(this.listTableData.map(item => item.id));
            // 删除所选
            this.tableList = this.tableList.filter(item => !temp.has(item.id));
            this.setPurchaseListData(
              this.tableList.length ? this.tableList[0] : ""
            );
            this.setDetailedTableList();
            this.setRemoveStatus(true);

            this.tableList.map(n => {
              this.testColumn(null, n, "blur", "inventoryCount");
            });
          })
          .catch(() => {});
      }
    },
    handleSubmit() {
      return new Promise((resolve, reject) => {
        if (!this.tableList.length) {
          reject("second");
          this.$showErrorMessage("采购清单不能为空");
        } else {
          // this.$refs.tableList.clearSelection();
          resolve(this.tableList);
        }
      });
    },
    // 选择库存
    planConfirm(arr) {
      let arr1 = arr.map(item => ({
        ...item,
        flag: true,
        materialId: item.id,
        unStockCount:
          item.actualStockCount !== null
            ? Number(item.actualStockCount).toFixed(3)
            : "",
        storageCount:
          item.storageCount !== null
            ? Number(item.storageCount).toFixed(3)
            : "",
        inventoryCount: Number(
          item.actualStockCount !== null ? item.actualStockCount : 0
        ).toFixed(3),
        unitPriceWithTax:
          item.unitPriceWithTax !== null
            ? Number(item.unitPriceWithTax).toFixed(2)
            : "",
        moneyWithTax:
          item.actualStockWithTax !== null
            ? Number(item.actualStockWithTax).toFixed(2)
            : "",

        // 盘点类型: 盘0 物资1
        inventoryType: 1
      }));
      this.tableList = uniqueByJson(
        [...this.tableList, ...arr1],
        "batchNumber"
      );
      this.setPurchaseListData(this.tableList[0]);
      this.setDetailedTableList();

      this.tableList.map(n => {
        this.testColumn(null, n, "blur", "inventoryCount");
      });
    },
    // 盘0库存
    planConfirmZero(arr) {
      let arr1 = arr.map(item => ({
        ...item,
        flag: true,
        materialId: item.id,
        unStockCount:
          item.actualStockCount !== null
            ? Number(item.actualStockCount).toFixed(3)
            : "",
        storageCount:
          item.storageCount !== null
            ? Number(item.storageCount).toFixed(3)
            : "",
        inventoryCount: Number(
          item.actualStockCount !== null ? item.actualStockCount : 0
        ).toFixed(3),
        unitPriceWithTax:
          item.unitPriceWithTax !== null
            ? Number(item.unitPriceWithTax).toFixed(2)
            : "",
        moneyWithTax:
          item.actualStockWithTax !== null
            ? Number(item.actualStockWithTax).toFixed(2)
            : "",

        // 盘点类型: 盘0 物资1
        inventoryType: 0
      }));
      this.tableList = uniqueByJson(
        [...this.tableList, ...arr1],
        "batchNumber"
      );
      this.setPurchaseListData(this.tableList[0]);
      this.setDetailedTableList();

      this.tableList.map(n => {
        this.testColumn(null, n, "blur", "inventoryCount");
      });
    },
    setDetailedTableList() {
      this.tableLoading = showLoading();

      this.$nextTick(() => {
        // 这样设置大量数据的表格
        this.$refs.tableList.reloadData(this.tableList);

        this.timer = setTimeout(() => {
          if (this.tableLoading !== null) {
            this.tableLoading.close();
            this.tableLoading = null;
          }
          // 重新布局表格
          this.$refs.tableList.doLayout();
        }, 500);
      });
    },
    //合计列算法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (this.summaryArr.includes(column.property)) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                let num = new this.$BigNumber(prev).plus(curr);
                return formatNumber(
                  num,
                  /数量|差异/.test(column.title) ? 3 : 2
                );
              } else {
                return Number(prev);
              }
            }, 0);
          }
          // else {
          //     sums[index] = "——";
          //   }
        }
      });

      // 计算差异 (是否盈亏 0 盘盈，1盘亏 2 盘0)
      const obj = columns.find(n => n.property === "inventoryDifferences");
      const values = data.map(item => Number(item[obj.property]));
      const sum = values.reduce(
        (prev, curr) => new this.$BigNumber(prev).plus(curr),
        0
      );
      this.setIsProfit(!sum ? 2 : /-/.test(sum) ? 1 : 0);

      // 表格的和
      return [sums];
    },
    // 给表头加必选标识
    must({ $rowIndex, column }) {
      if (["盘点数量"].includes(column.title)) {
        return "must";
      }
    },
    testColumn(e, row, eventType, nameModel) {
      if (eventType === "blur") {
        if (e !== null) {
          e.target.style.border = `1px solid ${
            row[nameModel] ? "#ccc" : "red"
          }`;
        }
        if (row[nameModel]) {
          const temp = formatNumber(Number(row[nameModel]), 3);
          if (this.getInputRule(temp)) {
            row[nameModel] = temp;
          } else {
            row[nameModel] = "0.000";
            row.moneyWithTax = "0.00";
            row.moneyWithoutTax = "0.00";
            row.inventoryDifferences = "0.000";
            // row.unStockCount = "0.000";
          }
          // 含税金额
          if (
            row.inventoryCount &&
            row.unitPriceWithTax &&
            this.getInputRule(row.inventoryCount) &&
            this.getInputRule(row.unitPriceWithTax)
          ) {
            // const newTaxRate = new this.$BigNumber(this.taxRateParams).plus(1);
            const price = new this.$BigNumber(row.inventoryCount).multipliedBy(
              row.unitPriceWithTax
            );

            row.moneyWithTax = setToFixed(price, 2);
          }
          // 不含税金额
          if (
            row.inventoryCount &&
            row.unitPriceWithoutTax &&
            this.getInputRule(row.inventoryCount) &&
            this.getInputRule(row.unitPriceWithoutTax)
          ) {
            const outPrice = new this.$BigNumber(
              row.inventoryCount
            ).multipliedBy(row.unitPriceWithoutTax);

            row.moneyWithoutTax = setToFixed(outPrice, 2);
          }
          // 差异
          if (
            row.inventoryCount &&
            row.unStockCount &&
            this.getInputRule(row.inventoryCount) &&
            this.getInputRule(row.unStockCount)
            // row.inventoryCount !== "0.000"
          ) {
            const differenceNumber = new this.$BigNumber(
              row.inventoryCount
            ).minus(row.unStockCount);

            row.inventoryDifferences = setToFixed(differenceNumber, 3);
          }
          // 算总和
          const count = this.tableList.every(_ => _.inventoryCount);
          const money = this.tableList.every(_ => _.moneyWithTax);
          const outMoney = this.tableList.every(_ => _.moneyWithoutTax);
          if (count && money && outMoney) {
            const setCount = setToFixed(
              this.tableList.reduce(
                (pre, cur) =>
                  new this.$BigNumber(pre).plus(Number(cur.inventoryCount)),
                0
              ),
              3
            );
            const setMoney = setToFixed(
              this.tableList.reduce(
                (pre, cur) =>
                  new this.$BigNumber(pre).plus(Number(cur.moneyWithTax)),
                0
              ),
              2
            );
            const setOutMoney = setToFixed(
              this.tableList.reduce(
                (pre, cur) =>
                  new this.$BigNumber(pre).plus(Number(cur.moneyWithoutTax)),
                0
              ),
              2
            );
            this.setInventoryCount({ setCount, setMoney, setOutMoney });
          }
        } else {
          row[nameModel] = "0.000";
          row.moneyWithTax = "0.00";
          row.moneyWithoutTax = "0.00";
          row.inventoryDifferences = "0.000";
          this.setInventoryCount({
            setCount: "",
            setMoney: "",
            setOutMoney: ""
          });
        }
      }
      if (eventType === "focus") {
        if (e !== null) {
          e.target.style.border = "1px solid #0089EF";
        }
      }
    },
    getInputRule(val) {
      const reg = /(^(\d{0,11})\.(\d{0,8})$)|(^\d{0,20}$)/;
      return reg.test(val);
    },
    // 采购清单选中数据   复选框选中
    listSelectTable(val) {
      this.listTableData = val;
    },
    ...mapActions([
      "setPurchaseListData",
      "setInventoryCount",
      "setReportChange",
      "setRemoveStatus",
      "setIsProfit"
    ])
  }
};
</script>

<style scoped lang="scss">
.operation-group {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
}

.ml {
  margin-left: 10px;
}
/deep/.el-input--suffix .el-input__inner {
  padding-right: 0;
}
::v-deep {
  .el-input input {
    padding-right: 50px;
  }
}
</style>
